$(function (){
    let alltion = [] , refereesb = [], refereesc = [];
    let num = 0 ,  nums = 0;
    function getModuleEntrance(){
        return $.ajax({
            cache: true,
            type: "post",
            url: "/jz-jinzhuan-disposition-module/selectModuleDetail",
            contentType:'application/json; charset=utf-8',
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {

            }
        })
    }

    $("#competitionType").change(async function (){
        num = 0;
        nums = 0;
        allocation();
        $("#addParams").html('');
        $("#addField").html('');
        $(".addListB p").click()
        $(".addListC p").click()
    })

    function allocation(){
        let maps = {
            track: '',
            competitionType: $('#competitionType').val()
        };
        //选择裁判
        return $.ajax({
            cache: true,
            type: "post",
            url: "/jzweb/examinationBatchCom/getUserReferee",
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(maps),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.code == 0) {
                    var format = [];

                    format = data.data.map(function (v) {
                        if( v ){
                            v.selected = false;
                            v.value = v.id;
                        }
                        return v;
                    })
                    return format;
                }
            }
        })
    }


    $(".addListB p").click(async function (){
        let str = '';
        num++;
        str = `
            <div class="templet">
                <div class="parseInset" style="margin-top: 10px;width: 100%;display:table;position: relative">
                    <div class="taskName col-sm-6" style="padding-left: 0">
                      <input name="topicName" class="form-control" autocomplete="off" type="text" placeholder="请输入名称">
                    </div>
                    <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                     onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                      <input name="score" class="form-control" type="text" autocomplete="off" placeholder="请输入分数" />
                    </div>
                    <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                      <textarea name="description" class="form-control" autocomplete="off" type="text" placeholder="请输入题目描述"></textarea>
                    </div>
                    <div class="remove">删除</div>
                </div>
                <div id="refer${num}"></div>  
               <select class="form-control query" name="" style="margin-top: 10px">

        `;

        let templet = await getModuleEntrance();
        templet.data?.map(function (v,k){
            str += `
                <option style="${k == 0 ? '':'display:none'}">请选择评分细则</option>
                <option value="${v.id}">${v.detailContent}</option>
            `;
        })

        str += `</select></div>`;

        $("#addParams").append(str);

        alltion = await allocation();
        alltion = alltion.data.map(function (v) {
            if( v ){
                v.selected = false;
                v.value = v.id;
            }
            return v;
        })

        xmSelect.render({
            el: '#refer'+ num,
            autoRow: true,
            name: 'refer'+ num,
            // max:3,
            data() {
                return alltion
            },
            maxMethod(seles, item) {
                layer.msg(`最多只能选择3个`)
            },
            on: function (data) {

                for(var i = 0; i < refereesc.length; i++){
                    if( refereesc[i].id == data.change[0].id ){
                        layer.msg('该裁判已分配在其他列表')
                        return false;
                    }
                }

                let arr = [];
                refereesb = data.arr;
                data.arr.map(function (v){
                    arr.push(v.id);
                })
                $("input[name='refer"+ num +"']").val(arr.join(','));

                // let params = {
                //     track:"B",
                //     ids: arr.join(',')
                // };
                // $.ajax({
                //     url:'/jzweb/examinationBatchCom/getUserReferee',
                //     contentType:'application/json; charset=utf-8',
                //     type:'post',
                //     data:JSON.stringify(params),
                //     success:function (res){
                //         refereesb = res.data
                //     },
                //     error:function (err){
                //         console.log(err.msg)
                //     }
                // })
            }
        })

    })

    $(".addListB p").click()

    $(".addListC p").click(async function (){
        nums++;
        let str = '';
        str = `
            <div class="templet">
                <div class="parseInset" style="margin-top: 10px;width: 100%;display:table;position: relative">
                    <div class="taskName col-sm-6" style="padding-left: 0">
                      <input name="topicName" class="form-control" autocomplete="off" type="text" placeholder="请输入名称">
                    </div>
                    <div class="taskScore col-sm-6" style="padding-left: 0;padding-right: 0">
<!--                    onkeyup= "this.value=this.value.replace(/[^\\d]/g,'')"-->
                      <input name="score" class="form-control" autocomplete="off" type="text" placeholder="请输入分数" >
                    </div>
                    <div class="taskDesc col-sm-12" style="padding-left: 0;padding-right: 0">
                        <textarea name="description" class="form-control" autocomplete="off" type="text" placeholder="请输入题目描述"></textarea>
                      </div>
                    <div class="remove">删除</div>
                </div>
                 <div id="refers${nums}"></div>
                 <select class="form-control query" name="" style="margin-top: 10px">
        `;

            let templet = await getModuleEntrance();
            templet.data?.map(function (v,k){
                str += `
                    <option style="${k == 0 ? '':'display:none'}">请选择评分细则</option>
                    <option value="${v.id}">${v.detailContent}</option>
                `;
            })

        str += `</select></div>`;

        $("#addField").append(str);
        alltion = await allocation();
        alltion = alltion.data.map(function (v) {
            if( v ){
                v.selected = false;
                v.value = v.id;
            }
            return v;
        })


        xmSelect.render({
            el: '#refers'+ nums,
            autoRow: true,
            name: 'refers'+ nums,
            // max:3,
            data() {
                return alltion
            },
            maxMethod(seles, item) {
                layer.msg(`最多只能选择3个`)
            },
            on: function (data) {
                for(var i = 0; i < refereesb.length; i++){
                    if( refereesb[i].id == data.change[0].id ){
                        layer.msg('该裁判已分配在其他列表')
                        return false;
                    }
                }
                refereesc = data.arr;
                let arrb = [];
                data.arr.map(function (v){
                    arrb.push(v.id);
                })
                $("input[name='refers"+ nums +"']").val(arrb.join(','));
            }
        })

    })

    $(".addListC p").click()

    $("body").on('click','.remove',function (){
        $(this).parents('.templet').remove();
    })

})


$("#btn").click(function (){
    save();
})

function save() {

    let disposition = [];

    $("#addParams").find(".templet").each(function (index,val){
        let idx = index+1;
        disposition.push({
            topicName: $(val).find('.taskName').find('input').val(),
            score: $(val).find('.taskScore').find('input').val(),
            description: $(val).find('.taskDesc').find('textarea').val(),
            refereeId:$('input[name="refer'+ idx +'"]').val(),
            detailId:$(val).find('.query').val(),
            type:'B'
        })
    })

    $("#addField").find(".templet").each(function (index,val){
        let idx = index+1;
        disposition.push({
            topicName: $(val).find('.taskName').find('input').val(),
            score: $(val).find('.taskScore').find('input').val(),
            description: $(val).find('.taskDesc').find('textarea').val(),
            refereeId:$('input[name="refers'+ idx +'"]').val(),
            detailId:$(val).find('.query').val(),
            type:'C'
        })
    })

    let maximum = 0;
    for(let i = 0; i <= disposition.length - 1; i++ ){
        maximum += parseFloat(disposition[i].score);
        // console.log(maximum);
        if( disposition[i].topicName == '' ){
            layer.msg('请填写题目名称');
            return false;
        }

        if( disposition[i].description == '' ){
            layer.msg('请填写题目描述');
            return false;
        }

        if( disposition[i].score == '' ){
            layer.msg('请填写分数');
            return false;
        }

        if( disposition[i].detailId == '' ||  disposition[i].detailId == "请选择评分细则"){
            layer.msg('请选择评分细则');
            return false;
        }

        if( disposition[i].refereeId == ''){
            layer.msg('请选择裁判');
            return false;
        }

    }

    if(maximum > $("#topicScore").val()){
        layer.msg('模块分值不能超过模版总分或小于0');
        return false;
    }

    if( maximum <= 0 ){
        layer.msg('模块分值不能超过模版总分或小于0');
        return false;
    }

    if( !$('#moduleName').val() ||  !$("#moduleType").val()){
        layer.msg('请输入名称或考试类型');
        return false;
    }

    if( !$('#competitionType').val() ){
        layer.msg('请选择竞赛类型');
        return false;
    }

    // disposition = JSON.stringify(disposition);

    let response = {
        moduleName: $('#moduleName').val(),
        moduleType: $("#moduleType").val(),
        dispositionTopic: disposition,
        totalScore: $("#totalScore").val(),
        competitionType: $("#competitionType").val()
    }
    response = JSON.stringify(response);
    $.ajax({
        cache: true,
        type: "POST",
        url: "/jz-jinzhuan-disposition-module/insert",
        data: response,// 你的formid
        async: false,
        headers: {
            'Content-Type':'application/json;charset=UTF-8'
        },
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success: function (data) {
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);

            } else {
                parent.layer.alert(data.msg)
            }

        }
    });

}